<?php

class WebsitesController extends Controller
{
	public function filters()
	{
		return array(
			'rights', // perform access control for CRUD operations
		);
	}
	public function allowedActions()
	{
		//return 'error';
	}
	
	public function actionIndex()
	{
		$model = new Websites('search');
		$model->unsetAttributes();  // clear any default values
		
		if(isset($_GET['Websites']))
			$model->attributes=$_GET['Websites'];

		$this->render('index',array(
			'model'=>$model,
		));
	}
	public function actionCreate()
	{
		$model = new Websites;
		$flag = 0; $flag1 = 0; $flag2 = 0;
		
		if(!empty($_POST['Websites']) && !empty($_POST['Prices']['id'])){
			
			$pageDemo_old = $model->attributes['pageDemo'];
			$image_old = $model->attributes['image'];
			$imageDetail_old = $model->attributes['imageDetail'];
			
			if(!empty(CUploadedFile::getInstance($model,'pageDemo')->name))
			{
				$path = realpath(Yii::app()->basePath.'/../upload/demo/'.$pageDemo_old);
				//if(file_exists($path) && !empty($pageDemo_old)) unlink($path);
				$model->attributes = $_POST['Websites'];
				$model->pageDemo = CUploadedFile::getInstance($model,'pageDemo');
				$image2 = $model->pageDemo;
				$arrImage = explode('.',$model->pageDemo->name);
				$imageType = $arrImage[count($arrImage)-1];
				$imageName = md5(uniqid()).'.'.$imageType;
				$model->md5PageDemo = $imageName;
				$model->type = $imageType;
				$model->size = $model->pageDemo->size;
				$model->pageDemo = $arrImage[count($arrImage)-2];
 				$images_path = Yii::getPathOfAlias('webroot').'/upload/demo/'.$imageName;
				$flag = 1;
			}else{
				$model->attributes = $_POST['Websites'];
				$model->pageDemo = $pageDemo_old;
			}
			
			if(!empty(CUploadedFile::getInstance($model,'image')->name))
			{
				$image_old = $model->attributes['image'];
				$path = realpath(Yii::app()->basePath.'/../upload/images/'.$image_old);
				if(file_exists($path) && !empty($image_old)) unlink($path);
				$model->image = CUploadedFile::getInstance($model,'image');
				$image1 = $model->image;
				$imageType = explode('.',$model->image->name);
				$imageType = $imageType[count($imageType)-1];
				$imageName = md5(uniqid()).'.'.$imageType;
				$model->image = $imageName;
				$images_path1 = Yii::getPathOfAlias('webroot').'/upload/images/'.$imageName;
				$flag1 = 1;
			}else{
				$model->image = $imageDetail_old;
			}
			
			if(!empty(CUploadedFile::getInstance($model,'imageDetail')->name))
			{
				$imageDetail_old = $model->attributes['imageDetail'];
				//$path = realpath(Yii::app()->basePath.'/../upload/images/'.$image_old);
				//if(file_exists($path) && !empty($image_old)) unlink($path);
				$model->imageDetail = CUploadedFile::getInstance($model,'imageDetail');
				$image3 = $model->imageDetail;
				$imageType = explode('.',$model->imageDetail->name);
				$imageType = $imageType[count($imageType)-1];
				$imageName = md5(uniqid()).'.'.$imageType;
				$model->imageDetail = $imageName;
				$images_path2 = Yii::getPathOfAlias('webroot').'/upload/images/'.$imageName;
				$flag2 = 1;
			}else{
				$model->imageDetail = $image_old;
			}
			
			$model->alias = alias($_POST['Websites']['name']);
			$model->created = time();
			$model->price =  $_POST['Websites']['price'];
			$model->priceFull =  $_POST['Websites']['priceFull'];
			
			if($model->save()){
				// Cap nhap so luong theme theo danh muc theme
				$model1 = CategoriesWebsite::model()->findByPk($model->id_categoiresWebsite);
				$model1->numberWebsite = $model1->numberWebsite+1;
				$model1->save();
				// luu hinh anh va source
				if($flag == 1)
				{
					$image2->saveAs($images_path);	
					$path = Yii::getPathOfAlias('webroot').'/upload/demo/'.$model->alias."_".$model->md5PageDemo;
					$zip = new ZipArchive;
					$res = $zip->open($images_path);
					$zip->extractTo($path);
					$zip->close();
					
				}
				if($flag1 == 1)
				{
					$image1->saveAs($images_path1);
				}
				
				if($flag2 == 1)
				{
					$image3->saveAs($images_path2);
				}
				// Them theme theo goi
				for($i=0;$i<count($_POST['Prices']['id']); $i++){
					$modelWebsitePrice =  new WebsitePrice;
					$modelWebsitePrice->id_website = $model->id;
					$modelWebsitePrice->id_price = $_POST['Prices']['id'][$i];
					$modelWebsitePrice->created = time();
					$modelWebsitePrice->save();
				}
				
				// Them hinh anh theo theme
				$arrImage = CUploadedFile::getInstancesByName('images');
				foreach($arrImage as $image){
					$modelImage = new ImagesWebsite;
					$modelImage->id_website = $model->id;
					$nameImage = explode(".", $image->name);
					$type = end($nameImage);
					$modelImage->image = md5(uniqid()).'.'.$type;
					$modelImage->created = time();
					$path = Yii::getPathOfAlias('webroot').'/upload/images/'.$modelImage->image;
					$image->saveAs($path);
					$modelImage->save();
				}
				
				Yii::app()->user->setFlash('success', translate('Thêm theme thành công.'));
				$this->redirect(PIUrl::createUrl('/admin/Websites'));
			}
		}
		
		$dataCategories = CategoriesWebsite::model()->getDataCategories();
		$modelPrice = new Prices;
		$dataPrice = Prices::model()->getDataPrice2();

		$this->render('create', array(
			"model"=>$model,
			"dataCategories" => $dataCategories,
			"dataPrice" => $dataPrice,
			"modelPrice" => $modelPrice,
		));
	}
	
	public function actionUpdate($id = null)
	{
		$model = Websites::model()->findByPk($id);
		//Lay danh sach goi cua them theo id
		$criteria = new CDBCriteria();
		$criteria->addCondition("id_website={$id}");
		$arrPrice_old = WebsitePrice::model()->findAll($criteria);
		$arrPriceOld =  array();
		foreach($arrPrice_old as $row){
			$arrPriceOld[] = $row->id_price;
		}

		$flag = 0; $flag1 = 0; $flag2 = 0;
		if(!empty($_POST['Websites'])){
			$pageDemo_old = $model->attributes['pageDemo'];
			$md5PageDemo = $model->attributes['md5PageDemo'];
			$image_old = $model->attributes['image'];
			$category_old = $model->attributes['id_categoiresWebsite'];
			$imageDetail_old = $model->attributes['imageDetail'];
			
			if(!empty(CUploadedFile::getInstance($model,'pageDemo')->name))
			{
				$path = realpath(Yii::app()->basePath.'/../upload/demo/'.$md5PageDemo);
				if(file_exists($path) && !empty($pageDemo_old)) unlink($path);
				$model->attributes = $_POST['Websites'];
				$model->pageDemo = CUploadedFile::getInstance($model,'pageDemo');
				$image2 = $model->pageDemo;
				$arrImage = explode('.',$model->pageDemo->name);
				$imageType = $arrImage[count($arrImage)-1];
				$imageName = md5(uniqid()).'.'.$imageType;
				$model->md5PageDemo = $imageName;
				$model->type = $imageType;
				$model->size = $model->pageDemo->size;
				$model->pageDemo = $arrImage[count($arrImage)-2];
 				$images_path = Yii::getPathOfAlias('webroot').'/upload/demo/'.$imageName;
				$flag = 1;
			}else{
				$model->attributes = $_POST['Websites'];
				$model->pageDemo = $pageDemo_old;
			}
			
			if(!empty(CUploadedFile::getInstance($model,'image')->name))
			{
				
				$path = realpath(Yii::app()->basePath.'/../upload/images/'.$image_old);
				if(file_exists($path) && !empty($image_old)) unlink($path);
				$model->image = CUploadedFile::getInstance($model,'image');
				$image1 = $model->image;
				$imageType = explode('.',$model->image->name);
				$imageType = $imageType[count($imageType)-1];
				$imageName = md5(uniqid()).'.'.$imageType;
				$model->image = $imageName;
				$images_path1 = Yii::getPathOfAlias('webroot').'/upload/images/'.$imageName;
				$flag1 = 1;
			}else{
				$model->image = $image_old;
			}
			
			if(!empty(CUploadedFile::getInstance($model,'imageDetail')->name))
			{
				$imageDetail_old = $model->attributes['imageDetail'];
				//$path = realpath(Yii::app()->basePath.'/../upload/images/'.$image_old);
				//if(file_exists($path) && !empty($image_old)) unlink($path);
				$model->imageDetail = CUploadedFile::getInstance($model,'imageDetail');
				$image3 = $model->imageDetail;
				$imageType = explode('.',$model->imageDetail->name);
				$imageType = $imageType[count($imageType)-1];
				$imageName = md5(uniqid()).'.'.$imageType;
				$model->imageDetail = $imageName;
				$images_path2 = Yii::getPathOfAlias('webroot').'/upload/images/'.$imageName;
				$flag2 = 1;
			}else{
				$model->imageDetail = $image_old;
			}
			
			$model->alias = alias($_POST['Websites']['name']);
			$model->updated = time();
			$model->price =  $_POST['Websites']['price'];
			$model->priceFull =  $_POST['Websites']['priceFull'];
			
			if($model->save()){
			
				if($category_old != $model->id_categoiresWebsite){
					$model1 = CategoriesWebsite::model()->findByPk($category_old);
					$model1->numberWebsite = $model1->numberWebsite-1;
					$model1->save();
					
					$model2 = CategoriesWebsite::model()->findByPk($model->id_categoiresWebsite);
					$model2->numberWebsite = $model2->numberWebsite+1;
					$model2->save();
				}
				
				if($flag == 1)
				{
					$image2->saveAs($images_path);	
					$path = Yii::getPathOfAlias('webroot').'/upload/demo/'.$model->alias."_".$model->md5PageDemo;
					$zip = new ZipArchive;
					$res = $zip->open($images_path);
					$zip->extractTo($path);
					$zip->close();
				}
				if($flag1 == 1)
				{
					$image1->saveAs($images_path1);
				}
				
				if($flag2 == 1)
				{
					$image3->saveAs($images_path2);
				}
				
				// Them theme theo goi
				for($i=0;$i<count($_POST['Prices']['id']); $i++){
					if(in_array($_POST['Prices']['id'][$i], $arrPriceOld) == false){
						$modelWebsitePrice =  new WebsitePrice;
						$modelWebsitePrice->id_website = $model->id;
						$modelWebsitePrice->id_price = $_POST['Prices']['id'][$i];
						$modelWebsitePrice->created = time();
						$modelWebsitePrice->save();
					}
				}
				// Xoa them theo goi
				for($i=0;$i<count($arrPriceOld);$i++){
					if(in_array($arrPriceOld[$i], $_POST['Prices']['id']) == false){
						$criteria =  new CDBCriteria;
						$criteria->addCondition("id_price={$arrPriceOld[$i]}");
						$model4=WebsitePrice::model()->find($criteria);
						$model4->delete();
					}
				}
				
				// Them hinh anh theo theme
				$arrImage = CUploadedFile::getInstancesByName('images');
				foreach($arrImage as $image){
					$modelImage = new ImagesWebsite;
					$modelImage->id_website = $model->id;
					$nameImage = explode(".", $image->name);
					$type = end($nameImage);
					$modelImage->image = md5(uniqid()).'.'.$type;
					$modelImage->created = time();
					$path = Yii::getPathOfAlias('webroot').'/upload/images/'.$modelImage->image;
					$image->saveAs($path);
					$modelImage->save();
				}
				
				Yii::app()->user->setFlash('success', translate('Cập nhật theme thành công.'));
				$this->redirect(PIUrl::createUrl('/admin/Websites'));
			}
		}
		
		$dataCategories = CategoriesWebsite::model()->getDataCategories();
		$modelPrice = new Prices;
		$dataPrice = Prices::model()->getDataPrice2();
		$modelPrice->id = $arrPriceOld;
		$criteria  = new CDBCriteria;
		$criteria->addCondition("id_website = {$id}");
		$arrImageTheme = ImagesWebsite::model()->findAll($criteria);

		$this->render('update', array(
			"model"=>$model,
			"dataCategories" => $dataCategories,
			"dataPrice" => $dataPrice,
			"modelPrice" => $modelPrice,
			'arrImageTheme' => $arrImageTheme,
		));
	}
	
	public function loadModel($id)
	{
		$model=Websites::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}
	
	public function actionDelete($id)
	{
		$model = Websites::model()->findByPk($id);
		$model1 = CategoriesWebsite::model()->findByPk($model->id_categoiresWebsite);
		$model1->numberWebsite = $model1->numberWebsite-1;
		$model1->save();
		
		$this->loadModel($id)->delete();
		
		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
	}
	
	public function actionDeleteImage($id=null){
		$model = ImagesWebsite::model()->findByPk($id);
		$path = realpath(Yii::app()->basePath.'/../upload/images/'.$model->image);
		if(file_exists($path) && !empty($image_old)) unlink($path);
		$model->delete();
		echo true;
	}
	
	// function delete rows
	public function actionDeleteAll($id){
		$arrIdNew = explode(",",$id);
		for($i=0; $i<count($arrIdNew); $i++){
			$model = Websites::model()->findByPk($arrIdNew[$i]);
			$model1 = CategoriesWebsite::model()->findByPk($model->id_categoiresWebsite);
			$model1->numberWebsite = $model1->numberWebsite-1;
			$model1->save();
			$this->loadModel($arrIdNew[$i])->delete();
		}
		if(!isset($_GET['ajax']))
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
	}
}